#include "settings.h"

#include <QApplication>
#include <QDir>

namespace MISystem
{
    SettingsManager& SettingsManager::instance()
    {
        static SettingsManager inst(qApp);
        return inst;
    }

    SettingsManager::SettingsManager(QObject* parent)
        : QObject(parent)
    {
        QString configPath = QApplication::applicationDirPath();
        QDir dir(configPath);
        if (!dir.exists()) {
            dir.mkpath(".");
        }

        QString configFile = configPath + "/settings.ini";
        _settings = new QSettings(configFile, QSettings::IniFormat);

        loadSettings();
    }

    SettingsManager::~SettingsManager()
    {
        saveSettings();
        delete _settings;
    }

    int SettingsManager::lackRemindThreshold() const
    {
        return _lackRemindThreshold;
    }

    int SettingsManager::stockWarningThreshold() const
    {
        return _stockWarningThreshold;
    }

    QString SettingsManager::systemStatus() const
    {
        return _systemStatus;
    }

    QString SettingsManager::operatorName() const
    {
        return _operatorName;
	}

    void SettingsManager::setLackRemindThreshold(int num)
    {
        _lackRemindThreshold = num;
    }

    void SettingsManager::setStockWarningThreshold(int num)
    {
        _stockWarningThreshold = num;
    }

    void SettingsManager::setSystemStatus(const QString& text)
    {
        _systemStatus = text;
    }

    void SettingsManager::setOperatorName(const QString& name)
    {
        _operatorName = name;
	}

    void SettingsManager::saveSettings()
    {
        if (!_settings) return;

        _settings->beginGroup("Settings");
        _settings->setValue("lackRemindThreshold", _lackRemindThreshold);
        _settings->setValue("stockWarningThreshold", _stockWarningThreshold);
        _settings->setValue("systemStatus", _systemStatus);
        _settings->setValue("operatorName", _operatorName);
        _settings->endGroup();
        _settings->sync();
    }

    void SettingsManager::loadSettings()
    {
        if (!_settings) return;

        _settings->beginGroup("Settings");
        _lackRemindThreshold = _settings->value("lackRemindThreshold", 0).toInt();
        _stockWarningThreshold = _settings->value("stockWarningThreshold", 0).toInt();
        _systemStatus = _settings->value("systemStatus", "").toString();
        _operatorName = _settings->value("operatorName", "").toString();
        _settings->endGroup();
    }
}